from typing import List, Dict, Any
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QGridLayout, QLabel, QScrollArea, QDialog, QPushButton
from PyQt5.QtGui import QPixmap, QColor
from PyQt5.QtCore import Qt


class HeroCard(QWidget):
    def __init__(self, hero: Dict[str, Any]):
        super().__init__()
        self.hero = hero
        self.setStyleSheet("QWidget { background: #221010; border: 1px solid #b71c1c; }")
        layout = QVBoxLayout(self)
        img = QLabel()
        img.setAlignment(Qt.AlignCenter)
        img.setMinimumHeight(120)
        src = hero.get("image", "")
        pix = QPixmap()
        if src.startswith("http"):
            # Load from URL via QPixmap's built-in (Qt supports http/https)
            pix.load(src)
        else:
            pix = QPixmap(src)
        if pix.isNull():
            # fallback to our 1x1 red placeholder ensures valid pixmap
            pix = QPixmap(1, 1)
            pix.fill(QColor("#8e1616"))
        img.setPixmap(pix.scaled(200, 120, Qt.KeepAspectRatioByExpanding, Qt.SmoothTransformation))
        name = QLabel(hero.get("name", ""))
        name.setAlignment(Qt.AlignCenter)
        intro = QLabel(hero.get("intro", ""))
        intro.setWordWrap(True)
        layout.addWidget(img)
        layout.addWidget(name)
        layout.addWidget(intro)


class HeroDialog(QDialog):
    def __init__(self, hero: Dict[str, Any]):
        super().__init__()
        self.setWindowTitle(hero.get("name", "英雄事迹"))
        self.setStyleSheet("QDialog { background: #160b0b; } QLabel { color: #f8f8f2; }")
        layout = QVBoxLayout(self)
        layout.addWidget(QLabel(f"姓名：{hero.get('name','')}"))
        years = []
        if hero.get("birth") is not None:
            years.append(str(hero.get("birth")))
        if hero.get("death") is not None:
            years.append(str(hero.get("death")))
        if years:
            layout.addWidget(QLabel("生卒：" + " - ".join(years)))
        layout.addWidget(QLabel("贡献：" + hero.get("contribution", "")))
        layout.addWidget(QLabel("名言：" + hero.get("quote", "")))
        layout.addWidget(QLabel("简介：" + hero.get("intro", "")))
        btn = QPushButton("关闭")
        btn.clicked.connect(self.accept)
        layout.addWidget(btn)


class HeroesView(QWidget):
    def __init__(self, heroes: List[Dict[str, Any]]):
        super().__init__()
        self._heroes = heroes
        outer = QVBoxLayout(self)

        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        container = QWidget()
        grid = QGridLayout(container)
        grid.setSpacing(12)

        for i, h in enumerate(heroes):
            card = HeroCard(h)
            card.mouseReleaseEvent = lambda e, hero=h: self._show_detail(hero)
            grid.addWidget(card, i // 4, i % 4)

        scroll.setWidget(container)
        outer.addWidget(scroll)

    def _show_detail(self, hero: Dict[str, Any]):
        dlg = HeroDialog(hero)
        dlg.exec_()

    def set_data(self, heroes: List[Dict[str, Any]]):
        self.__init__(heroes)

